package com.wf.mock.app.utils;

/**
 * @Title: AESUtil.java
 * @Package com.wafersystems.util
 * @Description: TODO(用一句话描述该文件做什么)
 * @author gelin
 * @date 2013-3-21 下午2:33:38
 */

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/** 
* @ClassName: AESUtil
* @Description: 加密解密算法
* @author gelin
*/
public final class AESUtil {
	
	private static final int KEY_SIZE = 128;
	
	private static final int OXFF = 0xFF;
	
	private static final int RADIX_HEX = 16;
	
	/**
	 * 私有构造体.
	* <p>Title: </p>
	* <p>Description: </p>
	 */
	private AESUtil() {
	}
	 // 加密    
    public static String encrypt(String sSrc, String sKey) throws Exception {    
        if (sKey == null) {    
            System.out.print("Key为空null");    
            return null;    
        }    
        // 判断Key是否为16位    
        if (sKey.length() != 16) { 
        	 System.out.print("sKey="+sKey+"长度为："+sKey.length()+"&Key长度不是16位");    
            return null;    
        }    
        byte[] raw = sKey.getBytes();    
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");    
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"    
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度    
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());  //parseByte2HexStr(result)
        return parseByte2HexStr(encrypted);
    }    
    
    // 解密    
    public static String decrypt(String sSrc, String sKey) throws Exception {    
        try {    
            // 判断Key是否正确    
            if (sKey == null) {    
                System.out.print("Key为空null");    
                return null;    
            }    
            // 判断Key是否为16位    
            if (sKey.length() != 16) {    
            	 System.out.print("sKey="+sKey+"长度为："+sKey.length()+"&Key长度不是16位");    
                return null;    
            }    
            byte[] raw = sKey.getBytes("ASCII");    
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");    
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");    
            IvParameterSpec iv = new IvParameterSpec("0102030405060708"    
                    .getBytes());    
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);    
            byte[] encrypted1 = parseHexStr2Byte(sSrc);
            try {    
                byte[] original = cipher.doFinal(encrypted1);    
                String originalString = new String(original);    
                return originalString;
            } catch (Exception e) {    
                System.out.println(e.toString());    
                return null;
            }    
        } catch (Exception ex) {    
            System.out.println(ex.toString());    
            return null;    
        }    
    }   
	/**
	 * 
	* @Title: encrypt
	* @Description: 加密
	* @param content 加密内容
	* @param password 密钥
	* @param @return
	* @return String
	* @throws
	 */
//	public static String encrypt(String content, String password) {
//		try {
//			KeyGenerator kgen = KeyGenerator.getInstance("AES");
////			kgen.init(KEY_SIZE, new SecureRandom(password.getBytes("utf-8")));
////			SecretKey secretKey = kgen.generateKey();
//			SecretKey secretKey = getKey(password);
//			byte[] enCodeFormat = secretKey.getEncoded();
//			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//			Cipher cipher = Cipher.getInstance("AES"); // 创建密码器
//			byte[] byteContent = content.getBytes("utf-8");
//			cipher.init(Cipher.ENCRYPT_MODE, key); // 初始化
//			byte[] result = cipher.doFinal(byteContent);
//			String encryptResultStr = parseByte2HexStr(result);
//			return encryptResultStr; // 加密
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		} catch (NoSuchPaddingException e) {
//			e.printStackTrace();
//		} catch (InvalidKeyException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} catch (IllegalBlockSizeException e) {
//			e.printStackTrace();
//		} catch (BadPaddingException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}

	/**
	 * 
	* @Title: decrypt
	* @Description: 解密
	* @param content 密文
	* @param password 密钥
	* @param @return
	* @return String
	* @throws
	 */
//	public static String decrypt(String content, String password) {
//		try {
//			KeyGenerator kgen = KeyGenerator.getInstance("AES");
////			kgen.init(KEY_SIZE, new SecureRandom(password.getBytes("utf-8")));
////			SecretKey secretKey = kgen.generateKey();
//			SecretKey secretKey = getKey(password);
//			byte[] enCodeFormat = secretKey.getEncoded();
//			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//			Cipher cipher = Cipher.getInstance("AES"); // 创建密码器
//			cipher.init(Cipher.DECRYPT_MODE, key); // 初始化
//			byte[] decryptFrom = parseHexStr2Byte(content);
//			byte[] result = cipher.doFinal(decryptFrom);
//			return new String(result, "utf-8"); // 加密
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		} catch (NoSuchPaddingException e) {
//			e.printStackTrace();
//		} catch (InvalidKeyException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} catch (IllegalBlockSizeException e) {
//			e.printStackTrace();
//		} catch (BadPaddingException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}

	/**
	 * 
	* @Title: parseByte2HexStr
	* @Description: 将二进制转换成16进制
	* @param buf - 二进制数组
	* @param @return
	* @return String
	* @throws
	 */
	public static String parseByte2HexStr(byte[] buf) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & OXFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 
	* @Title: parseHexStr2Byte
	* @Description: 将16进制转换为二进制
	* @param hexStr - 16进制数
	* @param @return
	* @return byte[]
	* @throws
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1) {
			return null;
		}
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), RADIX_HEX);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), RADIX_HEX);
			result[i] = (byte) (high * RADIX_HEX + low);
		}
		return result;
	}
	
	/**
	 * 
	* @Title: getKey
	* @Description: getkey
	* @param strKey -
	* @return SecretKey
	* @throws
	 */
	private static SecretKey getKey (String strKey) {
		try {
	          KeyGenerator _generator = KeyGenerator.getInstance("AES");
	           SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	          secureRandom.setSeed(strKey.getBytes());
	          _generator.init(128, secureRandom);
	              return _generator.generateKey();
	      }  catch (Exception e) {
	           throw new RuntimeException("初始化密钥出现异常 ");
	      }
	}

	/**
	 * 
	* @Title: main
	* @Description: 测试方法
	* @param args - 测试参数
	 */
//	public static void main(String[] args) {
//		String content = "Admin-wsm";
//		// 加密
//		System.out.println("加密前：" + content);
//		String encryptResultStr = encrypt(content, Consts.WAFER_KEY);
//		System.out.println("加密后：" + encryptResultStr);
//		// 解密
//		System.out.println("解密后：" + new String(decrypt(encryptResultStr, Consts.WAFER_KEY)));
//	}
}
